<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/9
 * Time: 11:59 AM
 */

namespace app\index\service;
use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\common\service\DownService;
use app\common\service\SkuService;
use think\Db;
use think\Exception;

class AllocateorderService
{
    static public function getList($param, $is_download = false)
    {
        try{
            $where = "where 1 = 1 ";
            $pageNumber = isset($param['page']) ? $param['page'] : 1;
            $pageData = isset($param['limit']) ? $param['limit'] : 20;
            $allocate_order_sn = isset($param['allocate_order_sn']) ? $param['allocate_order_sn'] : '';  //调拨单单号
            $id = isset($param['id']) ? $param['id'] : '';  // ID
            $code = isset($param['code']) ? $param['code'] : '';  //配送计划单号
            $allocate_name = isset($param['allocate_name']) ? $param['allocate_name'] : '';  //调出公司/店铺
            $base_shop_name = isset($param['base_shop_name']) ? $param['base_shop_name'] : '';  //调入店铺名称
            $base_shop_id = isset($param['base_shop_id']) ? $param['base_shop_id'] : '';  //调入店铺ID
            $status = isset($param['status']) ? $param['status'] : '';  //状态
            $offset = ($pageNumber - 1) * $pageData;
            $limit = " LIMIT $offset,$pageData";

            if (!empty($id)) {
                $id = trim($id);
                $where .= " AND id = $id";
            }
            if (!empty($allocate_order_sn)) {
                $allocate_order_sn = trim($allocate_order_sn);
                $where .= " AND allocate_order_sn = '{$allocate_order_sn}'";
            }
            if (!empty($code)) {
                $code = trim($code);
                $where .= " AND code = '{$code}'";
            }
            if (!empty($allocate_name)) {
                $allocate_name = trim($allocate_name);
                $where .= " AND allocate_name = '{$allocate_name}'";
            }
            if (!empty($base_shop_name)) {
                $base_shop_name = trim($base_shop_name);
                $where .= " AND base_shop_name = '{$base_shop_name}'";
            }
            if (!empty($base_shop_id)) {
                $base_shop_id = trim($base_shop_id);
                $where .= " AND base_shop_id = {$base_shop_id}";
            }
            if (!empty($status)) {
                $where .= " AND status = {$status}";
            }

            $sqlCount = "SELECT COUNT(id) num FROM allocate_order {$where}";
            $countArr = ToolModel::queryData($sqlCount);
            if (empty($countArr) || $countArr[0]['num'] == 0) {
                if ($is_download) exitJson(["code" => "500", "msg" => "无有效数据"]);
                return array('total' => 0, 'list' => array());
            }
            $fileds = 'id,allocate_order_sn,code,sku_type,allocate_name,base_warehouse_name as base_warehouse_name_out,
                      base_shop_name as base_shop_name_in,base_warehouse_name_in,
                      address_in,arrive_time,operator,update_time,create_time,status,type,
                      case status when 1 then "已完成" when -1 then "未完成" end status_name,
                      case type when 1 then "国家仓-店仓" when 2 then "店仓-店仓" end type_name';

            $sql = "SELECT {$fileds} FROM allocate_order {$where} ORDER BY id DESC {$limit}";
            if ($is_download) return "SELECT {$fileds} FROM allocate_order {$where} ORDER BY id DESC ";

            $list = ToolModel::queryData($sql);
            $data = array();
            $data['total'] = intval($countArr[0]['num']);
            $data['list'] = $list;

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 导出数据
     * @param $param
     * @return array
     * @author duanwenjie
     */
    static public function export($param)
    {
        $sql = self::getList($param,true);
        $title = array(
            'allocate_order_sn' => '调拨单号',
            'code' => '配送计划单号',
            'sku_type' => 'SKU种数',
            'allocate_name' => '调出公司/店铺',
            'base_warehouse_name_out' => '调出仓库',
            'base_shop_name_in' => '调入店铺',
            'base_warehouse_name_in' => '调入仓库',
            'arrive_time' => '预计到货时间',
            'status_name' => '状态'
        );

        $res = DownService::getData($sql,$title,'',$param);

        return $res;
    }

    /**
     * 获取店仓入库明细
     * @param $param
     * @return false|\PDOStatement|string|\think\Collection
     * @author duanwenjie
     */
    static public function getAllocateorderDetail($param)
    {
        $id = $param['id'];
        $res = self::getList($param);
        $res_detail = Db::name('allocate_order_detail')->field('*')->where('allocate_order_id','=',$id)->select();
        $data = array(
            "info" => $res['list'],
            "detail" => $res_detail
        );

        return $data;
    }


    /**
     * 配送计划、国家仓、SAP销售三种线路插入调拨单/店仓出库/店仓入库数据记录
     * @param $param
     * @return array
     * @author duanwenjie
     */
    static public function insertAllocateorderShopwarehouseoutData($param)
    {
        try{
            /*1：配送计划路线 2：国家仓路线 3：SAP销售路线*/
            $type = isset($param['type']) ? $param['type'] : '';
            if (empty($type)) return array("code" => 500, "msg" => "插入数据类型不能为空");
            if ($type == 1){
                $distribution_plan_id = isset($param['id']) ? $param['id'] : '';
                if (empty($distribution_plan_id)) return array("code" => 500, "msg" => "配送计划ID不能为空");

                return self::diaoboLine($distribution_plan_id);
            }elseif ($type == 2){
                $warehouse_country_id = isset($param['id']) ? $param['id'] : '';
                if (empty($warehouse_country_id)) return array("code" => 500, "msg" => "国家仓ID不能为空");

                return self::countryLine($warehouse_country_id);
            }elseif ($type == 3){
                $sap_order_id = isset($param['id']) ? $param['id'] : '';
                if (empty($sap_order_id)) return array("code" => 500, "msg" => "SAP订单ID不能为空");

                return self::sapLine($sap_order_id);
            }else{
                return array("code" => 500, "msg" => "插入数据类型有误");
            }
        }catch (Exception $e){
            trace($e->getMessage(), 'error');

            return array("code" => 500, "msg" => $e->getMessage());
        }
    }


    /**
     * 调拨单线
     * 调拨单插入数据记录、店仓出库插入未确定的数据记录
     * @param $distribution_plan_id
     * @return array
     * @author duanwenjie
     */
    static public function diaoboLine($distribution_plan_id)
    {
        try{
            $res = Db::name('distribution_plan')->alias('DP')
                ->join('distribution_plan_detail DPD','DP.id = DPD.distribution_plan_id','left')
                ->join('base_company BC','DP.company_id_out = BC.id','left') // 发货公司
                ->join('base_company BC2','DP.recieve_company = BC2.id','left') // 收货公司
                ->join('base_shop BS','DP.shop_id_rec = BS.id','left') // 收货店铺
                ->join('base_warehouse BW','DP.warehouse_id_out = BW.id','left') // 发货仓库
                ->join('base_warehouse BW2','DP.warehouse_id_rec = BW2.id','left') // 收货仓库
                ->field('DP.*,BC.company_name as company_name_out,BC2.company_name as company_name_in,BS.shop_name as shop_name_in,
            BW.warehouse_name as warehouse_name_out,BW2.warehouse_name as warehouse_name_in,BW2.address as address_in,
            BW.type as type_out,BW2.type as type_in,DPD.id as distribution_plan_detail_id,DPD.sku,DPD.sku_name,DPD.quantity,DPD.available_stock,DPD.price')
                ->where('DP.id','=',$distribution_plan_id)
                ->where('DP.status','=',2) // 2 :已审核
                ->where('DPD.status','=',1)
                ->select();
            $insert_allocate_data = array();
            $insert_allocate_detail_data = array();
            $insert_shopwarehouseout_data = array();
            if (!empty($res)){
                $allocate_order_sn = ToolModel::createSerialNumber('DB1'); // 调拨单号
                $batch = ToolModel::createSerialNumber('CK1'); // 出库批次号
                $diaobo_type = 0;
                $str = $res[0]['type_out'] . $res[0]['type_in'];
                /*仓库类型 1：店仓 2：国家仓*/
                if ($str == 21){
                    $diaobo_type = 1; // 国家仓-店仓
                }elseif ($str == 11){
                    $diaobo_type = 2; // 店仓-店仓
                }
                $insert_allocate_data = array(
                    "allocate_order_sn" => $allocate_order_sn,
                    "code" => $res[0]['code'],
                    "sku_type" => count($res), // SKU种类
                    "allocate_name" => $res[0]['company_name_out'],
                    "base_warehouse_id" => $res[0]['warehouse_id_out'],
                    "base_warehouse_name" => $res[0]['warehouse_name_out'],
                    "base_shop_id" => $res[0]['shop_id_rec'],
                    "base_shop_name" => $res[0]['shop_name_in'],
                    "base_warehouse_id_in" => $res[0]['warehouse_id_rec'],
                    "base_warehouse_name_in" => $res[0]['warehouse_name_in'],
                    "address_in" => $res[0]['address_in'],
                    "arrive_time" => $res[0]['distribution_time'], // 预计到货时间 => 需求配送日期
                    "operator" => $res[0]['operator'],
                    "type" => $diaobo_type // 调拨类型
                );
                $allocate_order_id = ToolModel::insertData($insert_allocate_data, 'allocate_order');
                if ($allocate_order_id){
                    foreach ($res as $value){
                        $insert_allocate_detail_data[] = array(
                            "allocate_order_id" => $allocate_order_id,
                            "sku" => $value['sku'],
                            "sku_name" => $value['sku_name'],
                            "allocate_quantity" => $value['quantity'], // 调拨数量 => 计划数量
                            "price" => $value['price']
                        );
                        $price = self::getBatchPrice($value['warehouse_id_out'],$value['sku'],$value['quantity']);
                        $insert_shopwarehouseout_data[] = array(
                            "batch" => $batch,
                            "base_warehouse_id" => $value['warehouse_id_out'],
                            "base_warehouse_name" => $value['warehouse_name_out'],
                            "business_sn" => $allocate_order_sn, // 业务单号取值为调拨单号
                            "sku" => $value['sku'],
                            "sku_name" => $value['sku_name'],
                            "need_quantity" => $value['quantity'], // 需求数量 => 计划数量
                            "quantity" => $value['quantity'], // 实际数量 => 计划数量
                            "price" => $price, // 取批次加权单价
                            "type" => 1, // 出库类型 1：调拨出库 2：销售出库
                            "operator" => $value['operator']
                        );
                    }
                    if (!empty($insert_allocate_detail_data)) $res2 = ToolModel::dbInsertOrUpdate('allocate_order_detail', $insert_allocate_detail_data);
                    /*只有调拨类型是 店仓=>店仓 才需要生成店仓出库单*/
                    if ($diaobo_type == 2){
                        if (!empty($insert_shopwarehouseout_data)) $res3 = ToolModel::dbInsertOrUpdate('shop_warehouse_out', $insert_shopwarehouseout_data);
                    }
                    self::saveLogs(1, 1, "AllocateorderService::diaoboLine", array("distribution_plan_id" => $distribution_plan_id), "操作成功，allocate_order_sn => {$allocate_order_sn}", $res[0]['operator']);
                    return array("code" => 1, "msg" => "操作成功", "data" => array("allocate_order_sn" => $allocate_order_sn));
                }else{
                    self::saveLogs(1, 0, "AllocateorderService::diaoboLine", array("distribution_plan_id" => $distribution_plan_id), "插入调拨单数据失败", $res[0]['operator']);
                    return array("code" => 500, "msg" => "插入调拨单数据失败");
                }
            }else{
                self::saveLogs(1, 0, "AllocateorderService::diaoboLine", array("distribution_plan_id" => $distribution_plan_id), "配送计划数据为空", isset($res[0]['operator']) ? $res[0]['operator'] : "");
                return array("code" => 500, "msg" => "配送计划数据为空");
            }
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            self::saveLogs(1, 0, "AllocateorderService::diaoboLine", array("distribution_plan_id" => $distribution_plan_id), $e->getMessage(), isset($res[0]['operator']) ? $res[0]['operator'] : "");
            return array("code" => 500, "msg" => $e->getMessage());
        }
    }


    /**
     * 国家仓线 (国家仓出库=>店仓入库)
     * 生成未确定的店仓入库记录
     * @param $warehouse_country_out_id
     * @return array
     * @author duanwenjie
     */
    static public function countryLine($warehouse_country_out_id)
    {
        try{
            $res = Db::name('warehouse_country_out')->alias('WCO')
                ->join('warehouse_country_out_detail WCOD','WCO.id = WCOD.warehouse_country_out_id','left')
                ->join('base_warehouse BW2','WCO.receipt_warehouse_id = BW2.id','left') // 发货仓库
                ->field('WCO.*,BW2.warehouse_name as warehouse_name_out,WCOD.id as warehouse_country_out_detail_id,
                         WCOD.sku,WCOD.sku_name,WCOD.quantity,WCOD.price')
                ->where('WCO.id','=',$warehouse_country_out_id)
                ->where('WCO.status','=',20) // 20 :已确定
                ->select();
            $insert_shopwarehousein_data = array();
            $insert_shopwarehousein_detail_data = array();
            if (!empty($res)){
                $batch = ToolModel::createSerialNumber('RK1'); // 入库批次号
                $type_ = ($res[0]['type'] == 10) ? 1 : 2; // 国家仓出库类型 10：调拨出库 20：盘亏出库 30：采销出库
                $insert_shopwarehousein_data = array(
                    "batch" => $batch,
                    "base_warehouse_id" => $res[0]['receipt_warehouse_id'], // 店仓收货 => 国家仓发货仓库
                    "base_warehouse_name" => $res[0]['warehouse_name_out'], // 店仓收货仓库名称
                    "business_sn" => $res[0]['bs_code'],
                    "sku_type" => count($res), // SKU种类
                    "type" => $type_, // 店仓入库类型 1：调拨入库 2：采购入库 3：盘盈入库
                    "operator" => $res[0]['user']
                );
                $shop_warehouse_in_id = ToolModel::insertData($insert_shopwarehousein_data, 'shop_warehouse_in');
                if ($shop_warehouse_in_id){
                    foreach ($res as $value){
                        $insert_shopwarehousein_detail_data[] = array(
                            "shop_warehouse_in_id" => $shop_warehouse_in_id,
                            "sku" => $value['sku'],
                            "sku_name" => $value['sku_name'],
                            "quantity" => $value['quantity'], // 数量 => 实际入库数量
                            "quantity_in" => $value['quantity'], // 入库数量 => 实际入库数量
                            "price" => $value['price']
                        );
                    }
                    if (!empty($insert_shopwarehousein_detail_data)) $res2 = ToolModel::dbInsertOrUpdate('shop_warehouse_in_detail', $insert_shopwarehousein_detail_data);
                    self::saveLogs(2, 1, "AllocateorderService::countryLine", array("warehouse_country_out_id" => $warehouse_country_out_id), "操作成功", $res[0]['user']);
                    return array("code" => 1, "msg" => "操作成功");
                }else{
                    self::saveLogs(2, 0, "AllocateorderService::countryLine", array("warehouse_country_out_id" => $warehouse_country_out_id), "插入店仓入库数据失败", $res[0]['user']);
                    return array("code" => 500, "msg" => "插入店仓入库数据失败");
                }
            }else{
                self::saveLogs(2, 0, "AllocateorderService::countryLine", array("warehouse_country_out_id" => $warehouse_country_out_id), "国家仓数据为空", isset($res[0]['user']) ? $res[0]['user'] : "");
                return array("code" => 500, "msg" => "国家仓数据为空");
            }
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            self::saveLogs(2, 0, "AllocateorderService::countryLine", array("warehouse_country_out_id" => $warehouse_country_out_id), $e->getMessage(), isset($res[0]['user']) ? $res[0]['user'] : "");
            return array("code" => 500, "msg" => $e->getMessage());
        }
    }


    /**
     * SAP线
     * 插入已确定的店仓出库记录
     * 更新库存成本相关数据
     * @param $sap_order_id
     * @return array
     * @author duanwenjie
     */
    static public function sapLine($sap_order_id)
    {
        try{
            $res = Db::name('sap_order')->alias('SO')
                ->join('sap_order_detail SOD','SO.id = SOD.order_id','left')
                ->join('base_warehouse BW2','SO.ship_warehouse_id = BW2.id','left') // 收货仓库
                ->field('SO.*,BW2.warehouse_name as warehouse_name_in,SOD.id as sap_order_detail_id,
            SOD.sku,SOD.sku_name,SOD.order_quantity as quantity,SOD.order_price as price')
                ->where('SO.id','=',$sap_order_id)
                ->select();
            $insert_shopwarehouseout_data = array();
            if (!empty($res)){
                $batch = ToolModel::createSerialNumber('CK1'); // 出库批次号
                foreach ($res as $value){
                    $insert_shopwarehouseout_data[] = array(
                        "batch" => $batch,
                        "base_warehouse_id" => $value['ship_warehouse_id'],
                        "base_warehouse_name" => $value['warehouse_name_in'],
                        "business_sn" => $value['order_sn_sap'],
                        "sku" => $value['sku'],
                        "sku_name" => $value['sku_name'],
                        "need_quantity" => $value['quantity'], // 需求数量 => 销售数量
                        "quantity" => $value['quantity'], // 实际数量 => 销售数量
                        "price" => $value['price'],
                        "status" => -1, // 状态 -1：未确定 1：已确定
                        "type" => 2, // 出库类型 1：调拨出库 2：销售出库
                        "operator" => "系统"
                    );
                }
                if (!empty($insert_shopwarehouseout_data)) $res2 = ToolModel::dbInsertOrUpdate('shop_warehouse_out', $insert_shopwarehouseout_data);
                /* ==店仓出库表数据插入完成后，将刚插入完成的店仓出库数据执行确定出库操作，更新库存成本相关数据，更新出库数据状态为1：已确定== */
                $res_ = Db::name('shop_warehouse_out')->where('batch', '=', $batch)->column('id,base_warehouse_id,batch,business_sn,sku,quantity,operator', 'id');
                if (!empty($res_)){
                    foreach ($res_ as $param_){
                        $param_['is_sure'] = true;
                        $param_['is_sap'] = true;
                        $result_ = ShopwarehouseoutService::edit($param_);
                        if (!empty($result_)){
                            /*如果店仓出库code !=1 ，则要中断SAP数据店仓出库操作*/
                                if ($result_['code'] != 1) {
                                self::saveLogs(3, 0, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), $result_['msg'], "系统");
                                return $result_;
                            }
                        }else{
                            self::saveLogs(3, 0, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), "SAP订单数据店仓出库异常", "系统");
                            return array("code" => 700, "msg" => "SAP订单数据店仓出库异常");
                        }
                    }
                }else{
                    self::saveLogs(3, 0, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), "SAP订单店仓出库数据为空", "系统");
                    return array("code" => 500, "msg" => "SAP订单店仓出库数据为空");
                }
                self::saveLogs(3, 1, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), "操作成功", "系统");
                return array("code" => 1, "msg" => "操作成功");
            }else{
                self::saveLogs(3, 0, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), "SAP数据为空", "系统");
                return array("code" => 500, "msg" => "SAP数据为空");
            }
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            self::saveLogs(3, 0, "AllocateorderService::sapLine", array("sap_order_id" => $sap_order_id), $e->getMessage(), "系统");
            return array("code" => 500, "msg" => $e->getMessage());
        }
    }


    /**
     * 店仓库存变动插入日志信息
     * @param $type
     * @param $status
     * @param $method
     * @param $request
     * @param $message
     * @param $operator
     * @author duanwenjie
     */
    static public function saveLogs($type, $status, $method, $request, $message, $operator)
    {
        $data = array(
            "type" => $type,
            "status" => $status,
            "method" => $method,
            "request" => json_encode($request),
            "message" => $message,
            "operator" => $operator
        );
        $res = ToolModel::dbInsertOrUpdate('shop_stock_logs', array($data));
    }

    /**
     * 盘点单店仓盘盈、盘亏出入库
     * @param $param
     * @return array
     * @author duanwenjie
     */
    static public function panYingPanKui($param)
    {
        try{
            $id = $param['id'];
            $error_msg = array();
            $res = Db::name('inventory')->alias('I')
                ->join('inventory_detail ID','I.id = ID.inventory_id','left')
                ->join('base_warehouse BW','I.warehouse_id = BW.id','left')
                ->field('I.inventory_sn,I.warehouse_id,I.operator,BW.warehouse_name,BW.type as ware_type,ID.*')
                ->where('I.id','=',$id)
                ->select();
            $shop_ins = array();
            $shop_outs = array();
            if (!empty($res)){
                foreach ($res as $value){
                    /*盘点差异数量数量大于0，则为店仓入库==>盘盈入库,小于等于0，则为店仓出库==>盘亏出库*/
                    if ($value['difference_quantity'] > 0){
                        $shop_ins[] = $value;
                    }else{
                        $shop_outs[] = $value;
                    }
                }
            }else{
                return returnArr(500,"盘点ID：({$id})对应的盘点数据不存在");
            }
            ToolModel::startTrans();
            /*店仓盘盈入库*/
            $insert_shopwarehousein_data = array();
            $insert_shopwarehousein_detail_data = array();
            if (!empty($shop_ins)){
                $batch = ToolModel::createSerialNumber('RK1'); // 入库批次号
                $insert_shopwarehousein_data = array(
                    "batch" => $batch,
                    "base_warehouse_id" => $shop_ins[0]['warehouse_id'], // 店仓收货 => 盘点单仓库发货仓库
                    "base_warehouse_name" => $shop_ins[0]['warehouse_name'], // 店仓收货仓库名称
                    "business_sn" => $shop_ins[0]['inventory_sn'],
                    "sku_type" => count($shop_ins), // SKU种类
                    "type" => 3, // 入库类型 1：调拨入库 2：采购入库 3：盘盈入库
                    "status" => -1, // 状态 -1：未确定 1：已确定
                    "operator" => $shop_ins[0]['operator']
                );
                $shop_warehouse_in_id = ToolModel::insertData($insert_shopwarehousein_data, 'shop_warehouse_in');
                if ($shop_warehouse_in_id){
                    foreach ($shop_ins as $shop_in){
                        $insert_shopwarehousein_detail_data[] = array(
                            "shop_warehouse_in_id" => $shop_warehouse_in_id,
                            "sku" => $shop_in['sku'],
                            "sku_name" => $shop_in['sku_name'],
                            "quantity" => $shop_in['difference_quantity'], // 数量 => 盘点差异数量
                            "quantity_in" => $shop_in['difference_quantity'], // 入库数量 => 盘点差异数量
                            "price" => $shop_in['unit_price']
                        );
                    }
                    if (!empty($insert_shopwarehousein_detail_data)) $res2 = ToolModel::dbInsertOrUpdate('shop_warehouse_in_detail', $insert_shopwarehousein_detail_data);
                    self::saveLogs(4, 1, "AllocateorderService::panYingPanKui", array("inventory_id" => $id), "操作成功", $shop_ins[0]['operator']);
                }else{
                    self::saveLogs(4, 0, "AllocateorderService::panYingPanKui", array("inventory_id" => $id), "盘点单盘盈插入店仓入库数据失败", $shop_ins[0]['operator']);
                    $error_msg[] = "盘点单盘盈插入店仓入库数据失败";
                }
            }

            /*店仓盘亏出库*/
            $insert_shopwarehouseout_data = array();
            if (!empty($shop_outs)){
                $batch2 = ToolModel::createSerialNumber('CK1'); // 出库批次号
                foreach ($shop_outs as $shop_out){
                    $insert_shopwarehouseout_data[] = array(
                        "batch" => $batch2,
                        "base_warehouse_id" => $shop_outs[0]['warehouse_id'],
                        "base_warehouse_name" => $shop_outs[0]['warehouse_name'],
                        "business_sn" => $shop_outs[0]['inventory_sn'],
                        "sku" => $shop_out['sku'],
                        "sku_name" => $shop_out['sku_name'],
                        "need_quantity" => $shop_out['difference_quantity'], // 需求数量 => 盘点差异数量
                        "quantity" => $shop_out['difference_quantity'], // 实际数量 => 盘点差异数量
                        "price" => $shop_out['unit_price'],
                        "status" => -1, // 状态 -1：未确定 1：已确定
                        "type" => 3, // 出库类型 1：调拨出库 2：销售出库 3：盘亏出库
                        "operator" => $shop_outs[0]['operator']
                    );
                }
                if (!empty($insert_shopwarehouseout_data)){
                    $res3 = ToolModel::dbInsertOrUpdate('shop_warehouse_out', $insert_shopwarehouseout_data);
                    self::saveLogs(4, 1, "AllocateorderService::panYingPanKui", array("inventory_id" => $id), "操作成功", $shop_outs[0]['operator']);
                }else{
                    self::saveLogs(4, 0, "AllocateorderService::panYingPanKui", array("inventory_id" => $id), "盘点单盘亏插入店仓出库数据失败", $shop_outs[0]['operator']);
                    $error_msg[] = "盘点单盘亏插入店仓出库数据失败";
                }
            }

            ToolModel::commit();
            return returnArr(1,join('</br>',$error_msg));
        }catch (Exception $e){
            ToolModel::rollback();
            self::saveLogs(4, 0, "AllocateorderService::panYingPanKui", array("inventory_id" => $id), $e->getMessage(), "系统");
            trace($e->getMessage(), 'error');
            return returnArr(600,$e->getMessage());
        }
    }

    /**
     * 获取店仓出库的加权批次单价
     * @param $base_warehouse_id
     * @param $sku
     * @param $quantity
     * @return float|int
     * @author duanwenjie
     */
    static public function getBatchPrice($base_warehouse_id, $sku, $quantity)
    {
        $check_shop_warehouse_cost = Db::name('shop_warehouse_cost')
            ->field('*')
            ->where('base_warehouse_id', '=', $base_warehouse_id)
            ->where('surplus_quantity', '>', 0)// 批次结余大于0的数据
            ->where('sku', '=', $sku)
            ->order('create_time', 'asc')// 时间升序，先入先出原则
            ->select();
        /*店仓出库，店仓成本更新成本明细，先入先出原则插入出库批次号，获取相应的批次加权单价*/
        $price = 0;
        if (!empty($check_shop_warehouse_cost)){
            $can_quantity = array_column($check_shop_warehouse_cost, 'surplus_quantity');
            $all_quantity = array_sum($can_quantity);
            if ($all_quantity < $quantity){
                return $price;
            }
            $need_quantity = $quantity; // 需要出库的数量
            foreach ($check_shop_warehouse_cost as $key => $value){
                // 大于0表示还需要再次选择另一个批次的SKU进行出库
                if ($need_quantity > 0){
                    /*SAP订单要计算入库批次加权单价 (入库批次数量/需要出库的数量) * 入库批次单价 */
                    $price += ($value['surplus_quantity'] > $need_quantity) ? ($need_quantity / $quantity) * $value['price'] : ($value['surplus_quantity'] / $quantity) * $value['price'];
                    $need_quantity = $need_quantity - $value['surplus_quantity'];
                }else{
                    break;
                }
            }
        }

        return $price;
    }
}